//---------------------------------------------------------------------------
/** メインフォーム
 */
//---------------------------------------------------------------------------
/*
 * Copyright (c) 1999 - 2005 shimitei
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
//---------------------------------------------------------------------------
#include <vcl.h>
#include <Registry.hpp>
#pragma hdrstop

#include "mainform.h"
#include "expform.h"
#include "aboutform.h"
#include "misc.h"
#include "spi_manage.h"
#include "xpi_manage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "DropEdit"
#pragma link "DropListBox"
#pragma resource "*.dfm"
TMainForm *MainForm;
//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
        : TForm(Owner)
{
    AnsiString path;
    // Susieプラグインの場所はEXEのあるフォルダ
    path = ExtractDirName( ParamStr( 0 ) ) + "\\" ;
    g_spiManager.loadAll( path.c_str() ) ;
    // 出力プラグインの場所はexp_plugフォルダ
    path += "exp_plug\\" ;
    g_xpiManager.loadAll( path.c_str() ) ;

    // コンボボックスに出力形式を入れる
    int count = g_xpiManager.getXpiCount() ;
    for (int i=0; i < count; i++)
    {
        Bit8ComboBox->Items->Add( g_xpiManager.getXpiInfo( i, 2 ) ) ;
    }
    Bit16ComboBox->Items->AddStrings( Bit8ComboBox->Items ) ;
}
//---------------------------------------------------------------------------
/** ファイルドロップ受付の登録
 * @param flagAccept 受け付けるならtrue
 */
void __fastcall TMainForm::setDropAccept(bool flagAccept)
{
    SrcListBox->DropAccept = flagAccept ;
    SrcEdit->DropAccept = flagAccept ;
    OutEdit->DropAccept = flagAccept ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FormCreate(TObject *Sender)
{
    setDropAccept( true ) ;
    loadOptions() ;

    /* コマンドライン処理 */
    int count = ParamCount() ;
    if ( count > 0 )
    {
        AnsiString param ;
        for (int i=0; i < count; )
        {
            i++ ;
            param = ParamStr( i ) ;
            DWORD at = GetFileAttributes( param.c_str() ) ;
            if ( at == 0xFFFFFFFF )
            {
                ; // 無効
            }
            else if ( at == FILE_ATTRIBUTE_DIRECTORY )
            {
                SrcListBox->Items->Add( param + "\\*.*" ) ;
            }
            else
            {
                SrcListBox->Items->Add( param ) ;
            }
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FormDestroy(TObject *Sender)
{
    // 念のため解除
    setDropAccept( false ) ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::startConvert(void)
{
    // XPIを登録
    g_xpiManager.setXpi8bit( Bit8ComboBox->ItemIndex ) ;
    g_xpiManager.setXpi16bit( Bit16ComboBox->ItemIndex ) ;


    TDialogForm* form = new TDialogForm(this) ;
    Enabled = false ;
    form->Visible = true ;
    form->init() ;
    form->play() ; // スレッド作りたくないので手抜き
    form->Visible = false ;
    Enabled = true ;
    delete form ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::StartButtonClick(TObject *Sender)
{
    if ( IsStartEnable() ) startConvert() ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::AboutButtonClick(TObject *Sender)
{
    TAboutForm* form = new TAboutForm(this) ;
    form->ShowModal() ;
    delete form ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FileAddButtonClick(TObject *Sender)
{
/** ファイルを追加
 */
    TOpenDialog *OpenDialog = new TOpenDialog(this) ;
    OpenDialog->Options << ofHideReadOnly << ofAllowMultiSelect	<< ofEnableSizing ;
    OpenDialog->Title = "変換するファイルを追加" ;
    if ( OpenDialog->Execute() )
    {
        SrcListBox->Items->AddStrings( OpenDialog->Files ) ;
        // 追加したファイル名を表示
        SrcListBox->TopIndex = SrcListBox->Items->Count -1 ;
    }
    delete OpenDialog ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::DeleteButtonClick(TObject *Sender)
{
/** リストから削除
 */
    // 選択されているものを削除
    int count = SrcListBox->Items->Count -1 ;
    // 削除すると順番がずれるので後ろから削除していく
    for (int i = count; i >= 0; i--)
    {
        if ( SrcListBox->Selected[ i ] )
        {
            SrcListBox->Items->Delete( i ) ;
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::AddButtonClick(TObject *Sender)
{
/** SrcEditの内容をSrcListBoxに追加
 */
    // ファイルの存在を確認する
    if ( SrcEdit->Text.IsEmpty() ) return ;
    if ( ExistsCheck( SrcEdit->Text ) == NO_EXISTS )
    {
        ::Message( "そのようなファイルは存在しません。", MB_ICONEXCLAMATION ) ;
        return ;
    }

    SrcListBox->Items->Add( SrcEdit->Text ) ;
    SrcListBox->TopIndex = SrcListBox->Items->Count -1 ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::CloseButtonClick(TObject *Sender)
{
    Close() ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::DirAddButtonClick(TObject *Sender)
{
/** フォルダを追加
 */
    AnsiString dirPath ;
    if ( ::SelectDirectory( "変換元フォルダを選択", "", dirPath ) )
    {
        SrcListBox->Items->Add( dirPath + "\\*.*" ) ;
        SrcListBox->TopIndex = SrcListBox->Items->Count -1 ;
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::OutButtonClick(TObject *Sender)
{
    AnsiString dirPath ;
    if ( ::SelectDirectory( "変換先フォルダを選択", "", dirPath ) )
    {
        OutEdit->Text = dirPath ;
    }
}
//---------------------------------------------------------------------------
bool __fastcall TMainForm::IsStartEnable(void)
{
/** 変換指定のチェック
 */
    if ( SrcListBox->Items->Count <= 0 )
    {
        ::Message("変換するファイルを指定してください。", MB_ICONINFORMATION ) ;
        return false;
    }

    if ( (Bit8ComboBox->ItemIndex == -1) || (Bit16ComboBox->ItemIndex == -1) )
    {
        ::Message( "出力形式を指定してください。", MB_ICONINFORMATION  ) ;
        return false ;
    }

    if ( OutEdit->Text.IsEmpty() )
    {
        ::Message( "変換先フォルダを指定してください。", MB_ICONEXCLAMATION ) ;
        return false ;
    }

    if ( ! ForceDirectories( OutEdit->Text) )
    {
        ::Message( "変換先フォルダを作成できません。", MB_ICONEXCLAMATION ) ;
        return false ;
    }

    return true ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::OpenButtonClick(TObject *Sender)
{
    TOpenDialog *OpenDialog = new TOpenDialog(this) ;
    OpenDialog->Options << ofHideReadOnly << ofEnableSizing ;
    OpenDialog->Title = "参照..." ;
    if ( OpenDialog->Execute() )
    {
        SrcEdit->Text = OpenDialog->FileName ;
    }
    delete OpenDialog ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::SaveButtonClick(TObject *Sender)
{
    saveOptions() ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::saveOptions(void)
{
/** 設定を保存
 */
    TRegistry *reg = new TRegistry ;
    //reg->RootKey = HKEY_CURRENT_USER ;
    reg->OpenKey( "\\Software\\shimitei\\abc", true ) ;

    reg->WriteString( "OutDir",  OutEdit->Text ) ;
    reg->WriteBool( "Overwrite", OverWriteCB->Checked ) ;
    reg->WriteBool( "ArcOut",    UnknownOutputCB->Checked ) ;
    reg->WriteString( "bit8",    Bit8ComboBox->Items->Strings[Bit8ComboBox->ItemIndex] ) ;
    reg->WriteString( "bit16",   Bit16ComboBox->Items->Strings[Bit16ComboBox->ItemIndex] ) ;

    reg->CloseKey() ;
    delete reg ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::loadOptions(void)
{
/** 設定を読み込み
 */
    TRegistry *reg = new TRegistry ;
    //reg->RootKey = HKEY_CURRENT_USER ;
    reg->OpenKey( "\\Software\\shimitei\\abc", true ) ;

    // このアプリケーションでは使用しないがXPIフォルダの場所を書き込む
    reg->WriteString( "XPIPath", ExtractDirName( ParamStr( 0 ) ) + "\\exp_plug\\" ) ;

    // 変換先フォルダ
    if ( reg->ValueExists( "OutDir" ) )
    {
        OutEdit->Text = reg->ReadString( "OutDir" ) ;
    }
    // 上書き確認
    if ( reg->ValueExists( "Overwrite" ) )
    {
        OverWriteCB->Checked = reg->ReadBool( "Overwrite" ) ;
    }
    // 未知の形式も出力
    if ( reg->ValueExists( "ArcOut" ) )
    {
        UnknownOutputCB->Checked = reg->ReadBool( "ArcOut" ) ;
    }
    // 出力形式
    AnsiString format ;
    if ( reg->ValueExists( "bit8" ) )
    {
        format = reg->ReadString( "bit8" ) ;
        setFormat( Bit8ComboBox, format ) ;
    }
    if ( reg->ValueExists( "bit16" ) )
    {
        format = reg->ReadString( "bit16" ) ;
        setFormat( Bit16ComboBox, format ) ;
    }

    reg->CloseKey() ;
    delete reg ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::setFormat(TComboBox *comboBox, const AnsiString &format)
{
    int count = comboBox->Items->Count ;
    for (int i=0; i < count; i++)
    {
        if ( comboBox->Items->Strings[i] == format )
        {
            comboBox->ItemIndex = i ;
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::SrcListBoxDropFiles(TObject *Sender,
      TStringList *DropFileList)
{
/** ファイルのドロップ受け取り
 */
    int count = DropFileList->Count ;
    AnsiString str ;
    for (int i=0; i < count; i++)
    {
        str = DropFileList->Strings[ i ] ;
        switch ( ExistsCheck( str ) )
        {
            case IS_DIR:
                SrcListBox->Items->Add( str + "\\*.*" ) ;
                break ;
            case IS_FILE:
                SrcListBox->Items->Add( str ) ;
                break ;
            default:
                ;
        }
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::SrcEditDropFiles(TObject *Sender,
      char *DropFileName)
{
/** ファイルのドロップ受け取り
 */
    ((TDropEdit *)Sender)->Text = DropFileName ;
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::abc8setButtonClick(TObject *Sender)
{
/** 出力プラグインの設定
 */
    if ( Bit8ComboBox->ItemIndex == -1 ) return ;
    if ( ! g_xpiManager.xpiConfig( Bit8ComboBox->ItemIndex, Handle, 1 ) )
    {
        ::Message( "このプラグインには設定がありません。", MB_ICONINFORMATION ) ;
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::abc16setButtonClick(TObject *Sender)
{
/** 出力プラグインの設定
 */
    if ( Bit16ComboBox->ItemIndex == -1 ) return ;
    if ( ! g_xpiManager.xpiConfig( Bit16ComboBox->ItemIndex, Handle, 1 ) )
    {
        ::Message( "このプラグインには設定がありません。", MB_ICONINFORMATION ) ;
    }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::ImportListButtonClick(TObject *Sender)
{
/** リスト取り込み
 */
    TOpenDialog *OpenDialog = new TOpenDialog(this) ;
    OpenDialog->Options << ofHideReadOnly << ofEnableSizing ;
    OpenDialog->Title = "リスト取り込み" ;
    if ( OpenDialog->Execute() )
    {
        TStringList *list = new TStringList() ;
        list->LoadFromFile( OpenDialog->FileName ) ;
        SrcListBox->Items->AddStrings( list ) ;
        SrcListBox->TopIndex = SrcListBox->Items->Count -1 ;
        delete list ;
    }
    delete OpenDialog ;
}
//---------------------------------------------------------------------------

